package com.example.testproject.activity

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.testproject.R
import com.example.testproject.adapter.MqttAdapter
import com.example.testproject.bean.MqttBean
import com.jinyx.mqtt.*
import kotlinx.android.synthetic.main.activity_mqtt.*

/**
 *
 * @ClassName: MqttActivity
 * @Author: android 超级兵
 * @CreateDate: 11/23/21$ 9:50 AM$
 * TODO mqtt与本地服务器的长链接
 */
class MqttActivity : AppCompatActivity(), OnMqttMsgListener,
    OnMqttStatusChangeListener {

    private val mqttListTemp = ArrayList<MqttBean>()

    private lateinit var mqttAdapter: MqttAdapter

    private lateinit var mqttHelper: IMqtt
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mqtt)
        supportActionBar?.hide()

        // TestExamTopicAdapter
        // testExamItem.getQuestion().getTestResult().getAnswer

        mqttRv.layoutManager = LinearLayoutManager(this)
        mqttAdapter = MqttAdapter(mqttListTemp)
        mqttRv.adapter = mqttAdapter

        /*
         * 作者:android 超级兵
         * 创建时间: 11/23/21 10:47 AM
         * TODO 初始化mqtt配置
         */
        buildMqtt()

        /*
         * 作者:android 超级兵
         * 创建时间: 11/23/21 10:55 AM
         * TODO 发送按钮
         */
        submitBt.setOnClickListener {
            val content: String? = editInput.text?.toString()
            if (content.isNullOrEmpty()) {
                Toast.makeText(this, "请输入要发送的内容", Toast.LENGTH_SHORT).show()
            } else {
                mqttHelper.pubMessage(MqttHelper.TOPIC, content.toByteArray())
                editInput.setText("")
            }


        }
    }

    private fun buildMqtt() {
        val options = MqttOptions(
            serviceUrl = "tcp://broker.emqx.io:1883",
            username = "123456",
            password = "123456",
            clientId = "android-${System.currentTimeMillis()}",
            willTopic = MqttHelper.TOPIC,
            willMsg = "你好我是android端,连接成功拉"
        )

        mqttHelper = MqttHelper(this, options)
        mqttHelper.addOnMsgListener(this)
        mqttHelper.addOnStatusChangeListener(this)
        mqttHelper.connect()
    }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/23/21 10:24 AM
     * TODO 接收到的消息
     */
    override fun onSubMessage(topic: String, payload: ByteArray) {
        val string = String(payload)
        if (topic == MqttHelper.TOPIC) {
            // 接收到消息
            mqttAdapter.addData(MqttBean(string, MqttAdapter.RIGHT_USER))
        } else {
            // 发送消息
            mqttAdapter.addData(MqttBean(string, MqttAdapter.LEFT_SERVICE))
        }

        // recyclerView 移动到最后一个位置
        mqttRv.smoothScrollToPosition(mqttAdapter.data.size - 1)
    }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/23/21 10:24 AM
     * TODO 发送消息
     */
    override fun onPubMessage(payload: ByteArray) {
        val string = String(payload)
        Log.i("szj收到消息1", string)
        // TODO 发送成功后在 onSubMessage() 返回
    }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/23/21 10:24 AM
     * TODO  连接状态
     *  [MqttStatus.SUCCESS]    // 连接成功
     *  [MqttStatus.FAILURE]    // 连接失败
     *  [MqttStatus.LOST]   // 连接中断
     */
    override fun onChange(state: MqttStatus, throwable: Throwable?) {
        // 只有连接成功才可以点击
        editInput.isEnabled = state == MqttStatus.SUCCESS
        submitBt.isEnabled = state == MqttStatus.SUCCESS

        if (state == MqttStatus.SUCCESS) {
            // 连接成功订阅主题
            mqttHelper.subscribe(MqttHelper.TOPIC_SUBSCRIBE)
            txtTitle?.text = String.format("连接成功!!")
        } else if (state == MqttStatus.LOST) {
            txtTitle?.text = "连接中断..."
        } else {
            txtTitle?.text = "连接失败..."
        }
    }


    override fun onDestroy() {
        mqttHelper.disConnect()
        super.onDestroy()
    }
}